<?php

declare(strict_types=1);

namespace Plugin\Attractions\AttractionManagement\Aspect;

use Plugin\Attractions\AttractionManagement\Aspect\CheckJwtToken;
use App\Exception\BusinessException;
use App\Http\Common\ResultCode;
use Common\Common;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\AbstractAspect;
use Psr\Container\ContainerInterface;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\HttpServer\Request;

#[Aspect]
class CheckJwtTokenAspect extends AbstractAspect
{
    public array $classes = [
        
    ];

    public array $annotations = [
        CheckJwtToken::class,
    ];
    public function __construct(protected ContainerInterface $container, protected Request $request)
    {
    }

    public function process(ProceedingJoinPoint $proceedingJoinPoint)
    {
        if (isset($proceedingJoinPoint->getAnnotationMetadata()->method[CheckJwtToken::class])) {
            $token = $this->request->getHeaderLine('Authorization');
            if (!$token) {
                throw new BusinessException(ResultCode::UNAUTHORIZED);
            }
        }
        $jwtData = Common::parseJwt($token);
        if (!$jwtData) {
            throw new BusinessException(ResultCode::UNAUTHORIZED);
        }
        return $proceedingJoinPoint->process();
    }
}
